import datetime
import os
import time

from openpyxl import Workbook

import airfly
import pandas as pd

import getFromHtml
import getSearchId


def loadLineAllData(key, searchId, pages, host):
    allPageData = []
    for page in pages:
        lineInfo = airfly.loadLineInfo(key, searchId, page, host)
        allPageData.extend(lineInfo)
    return allPageData


def run(lines, pages, date, host):
    allLineData = []
    for line in lines:
        departure = line[0]
        arrival = line[1]
        searchUrl = '/flights/' + departure + '-' + arrival + '/' + date
        data = getFromHtml.getDatas(host, departure, arrival, date)

        time.sleep(1)
        # data = loadLineAllData(searchUrl, searchId, pages, host)
        allLineData.extend(data)

    folder_path = './data/' + str(datetime.datetime.now().strftime("%Y%m%d"));
    if not os.path.exists(folder_path):
        # 文件夹不存在，创建文件夹
        os.makedirs(folder_path)
    excel_filename = folder_path + '/' + host + '_' + str(
        datetime.datetime.now().strftime("%Y%m%d_%H_%M_%S")) + '.xlsx'

    df = pd.DataFrame(allLineData)
    df.to_excel(excel_filename, index=False, header=True, engine='openpyxl')


